// pages/confirmorder/confirmorder.js
var app = getApp()

Page({

    /**
     * 页面的初始数据
     */
    data: {
        agreement: false,
        isBalance: false,
        isBalaDis: false,
        info: {
            product: {
                id: '',
                price: '',
                name: '',
                main_img: '',
                time: '',
                unit: '',
                service_category_id: '',
                content: ''
            },
            address: {
                id: '',
                name: '',
                phone: '',
                address: '',
                province_id: '',
                city_id: '',
                district_id: ''
            },
            time: {
                start_at: '',
                end_at: '',
                hours: 1
            },
            cleaner: {
                id: '',
                wx_avatar_url: '',
                real_name: ''
            },
            coupon: {
                id: '',
                price: '',
            },
            remark: '',
            totalPrice: 0,
            textarea: true,
            balance: 0,
        }
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        console.log(options.info)
        this.setData({
            info: JSON.parse(options.info)
        })
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        this.initConfirm()
    },

    /**
     * 初始化页面
     */
    initConfirm: function () {
        let _this = this,
            info = this.data.info,
            balance = "",
            address = "",
            totalPrice = ""

        wx.showLoading({
            title: app.globalData.loadText
        })
        app.getAccessToken(app.getPageUrl(getCurrentPages())).then(function (accessToken) {
            wx.request({
                url: app.globalData.hostAPI + '/v1/finance/balance?access_token=' + accessToken,
                success: balance => {
                  if (balance.data.status === 1) {
                        balance = balance.data.data.balance
                        if (_this.data.info.address.id) {
                            wx.request({
                                url: app.globalData.hostAPI + '/v1/addr/default?access_token=' + accessToken,
                                success: addr => {
                                    if (addr.data.status === 1) {
                                        _this.setData({
                                            'info.address': addr.data.data.default
                                        })
                                    }
                                }
                            })
                        } else {
                            address = _this.data.info.address
                        }

                        if (info.coupon.id == '') {
                            totalPrice = info.product.price * info.time.hours
                        } else {
                            totalPrice = (info.product.price * info.time.hours) - info.coupon.price
                        }

                        if (parseInt(balance) < parseInt(totalPrice)) {
                            _this.setData({
                                isBalaDis: true
                            })
                        }

                        _this.setData({
                            'info.address': address,
                            'info.totalPrice': totalPrice
                        }, () => {
                            wx.hideLoading()
                        })

                    } else {
                        wx.showToast({
                            title: res.data.msg,
                            success: res => {
                                _this.onLoad()
                            }
                        })
                    }
                }
            })
        })
    },

    getBalance: function () {
        let that = this
        app.getAccessToken(app.getPageUrl(getCurrentPages())).then(function (accessToken) {
            wx.request({
                url: app.globalData.hostAPI + '/v1/finance/balance?access_token=' + accessToken,
                success: res => {
                    if (res.data.status === 1) {
                        if (parseInt(res.data.data.balance) < parseInt(that.data.info.totalPrice)) {
                            that.setData({
                                isBalaDis: true
                            }, () => {
                                that.getDefaultAddr()
                            })
                        }
                    }
                }
            })
        })
    },

    /**
     * 获取默认地址
     */
    getDefaultAddr: function () {
        let that = this
        app.getAccessToken(app.getPageUrl(getCurrentPages())).then(function (accessToken) {
            wx.request({
                url: app.globalData.hostAPI + '/v1/addr/default?access_token=' + accessToken,
                success: res => {
                    if (res.data.status === 1) {
                        that.setData({
                            'info.address': res.data.data.default
                        }, () => {
                            that.totalJs()
                            wx.hideLoading()
                        })
                    }
                }
            })
        })
    },

    /**
     * 选择服务时间
     */
    time: function () {
        wx.reLaunch({
            url: '/pages/confirm/chosentime/chosentime?info=' + JSON.stringify(this.data.info),
        })
    },

    /**
     * 选择地址
     */
    address: function () {
        wx.navigateTo({
            url: '/pages/user/address/address?info=' + JSON.stringify(this.data.info),
        })
    },

    /**
     * 选择保洁
     */
    clean: function () {
        wx.reLaunch({
            url: '/pages/cleaner/list?info=' + JSON.stringify(this.data.info),
        })
    },

    /**
     * coupon
     */
    coupon: function () {
        wx.navigateTo({
            url: '/pages/user/mycoupon/mycoupon?info=' + JSON.stringify(this.data.info),
        })
    },

    /**
     * 同意协议
     */
    checkRadio: function (e) {
        this.setData({
            agree: e.detail
        })
    },

    /**
     *
     */
    checkBalance: function (e) {
        if (this.data.isBalance != e.detail) {
            this.setData({
                isBalance: e.detail
            })
        } else {
            console.log(2)
            this.setData({
                isBalance: '2'
            })
        }

    },

    /**
     *
     */
    toPay: function () {
        let that = this,
            myApp = that.data.info,
            mobile

        if (myApp.address.id == '') {
            wx.showToast({
                icon: 'none',
                title: '请选择服务地址',
            })
            return false
        }

        if (myApp.time.start_at == '') {
            wx.showToast({
                icon: 'none',
                title: '请选择服务时间',
            })
            return false
        }

        if (myApp.cleaner.id == '') {
            wx.showToast({
                icon: 'none',
                title: '请选择保洁',
            })
            return false
        }

        if (!that.data.agreement) {
            wx.showToast({
                icon: 'none',
                title: '请阅读用户协议',
            })
            return false
        }

        wx.showLoading({
            mask: true,
            title: app.globalData.loadText,
        })

        app.getAccessToken(app.getPageUrl(getCurrentPages())).then(function (accessToken) {
            wx.request({
                url: app.globalData.hostAPI + '/v1/wxpay/to-order-v2?access_token=' + accessToken,
                data: {
                    product_id: myApp.product.id,
                    addr_id: myApp.address.id,
                    start_at: myApp.time.start_at,
                    end_at: myApp.time.end_at,
                    hours: myApp.time.hours,
                    provider_id: myApp.cleaner.id,
                    customer_coupon_id: myApp.coupon.id,
                    leave_message: myApp.remark,
                    is_balance: that.data.isBalance
                },
                success: res => {
                    if (res.data.status === 1) {
                        wx.hideLoading()
                        if (res.data.data.appId) {
                            wx.requestPayment({
                                timeStamp: res.data.data.timeStamp,
                                nonceStr: res.data.data.nonceStr,
                                package: res.data.data.package,
                                signType: res.data.data.signType,
                                paySign: res.data.data.paySign,
                                success: res1 => {
                                    wx.showModal({
                                        title: '提示',
                                        content: '支付成功',
                                        success: res2 => {
                                            if (res2.confirm) {
                                                wx.request({
                                                    url: app.globalData.hostAPI + '/v1/order/send-message?access_token=' + accessToken,
                                                    data: {
                                                        out_trade_no: res.data.data.out_trade_no
                                                    }
                                                })
                                                wx.reLaunch({
                                                    url: '/pages/success/success',
                                                })
                                            }
                                        }
                                    })
                                },
                                fail: err => {
                                    wx.showModal({
                                        title: '提示',
                                        content: '支付失败，稍后再试',
                                        success: res => {
                                            if (res.confirm) {
                                                wx.switchTab({
                                                    url: '/pages/index/index',
                                                })
                                            }
                                        }
                                    })
                                }
                            })
                        } else {
                            wx.showModal({
                                title: '提示',
                                content: '支付成功',
                                success: res2 => {
                                    if (res2.confirm) {
                                        wx.request({
                                            url: app.globalData.hostAPI + '/v1/order/send-message?access_token=' + accessToken,
                                            data: {
                                                out_trade_no: res.data.data.out_trade_no
                                            }
                                        })
                                        wx.reLaunch({
                                            url: '/pages/success/success',
                                        })
                                    }
                                }
                            })
                        }
                    } else if (res.data.status === 2) {
                        wx.hideLoading()
                        wx.showModal({
                            title: '提示',
                            content: '该保洁时间段被占用，请重新选择或更换保洁',
                        })
                    } else {
                        wx.hideLoading()
                        wx.showModal({
                            title: '提示',
                            content: '未知错误',
                        })
                    }
                }
            })
        })
    },

    totalJs: function () {
        let that = this,
            total = 0
        if (that.data.info.coupon.id == '') {
            total = that.data.info.product.price * that.data.info.time.hours
        } else {
            total = (that.data.info.product.price * that.data.info.time.hours) - that.data.info.coupon.price
        }
        that.setData({
            'info.totalPrice': total
        })
    },

    /**
     * 备注
     */
    remakValue: function (e) {
        this.setData({
            'info.remark': e.detail.value
        })
    },

    agreement: function (e) {
        if (this.data.agreement) {
            this.setData({
                agreement: false
            })
        } else {
            this.setData({
                agreement: true
            })
        }
    },

    /**
     *
     */
    isBalance: function (e) {
        if (this.data.isBalance) {
            this.setData({
                isBalance: false
            })
        } else {
            this.setData({
                isBalance: true
            })
        }
    },

    goHome: function () {
        wx.switchTab({
            url: '/pages/index/index',
        })
    },

    goBack: function () {
        let _this = this
        wx.redirectTo({
            url: '/pages/product/product?info=' + JSON.stringify(_this.data.info),
        })
        // wx.navigateTo({
        //   url: '/pages/product/product?info=' + JSON.stringify(_this.data.info),
        // })
        // wx.reLaunch({
        //   url: '/pages/product/product?info=' + JSON.stringify(_this.data.info),
        // })
    }
})
